package objects

import (
	"compress/gzip"
	"crypto/sha256"
	"dos_framework/dataServer/locate"
	"encoding/base64"
	"path/filepath"

	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
)

/*
get函数负责处理HTTP的GET请求，从本地磁盘读取内容并将其作为HTTP的响应正文输出
1.通过os.Open打开文件f，打开失败，返回HTTP 404，如果打开成功，则
2.将文件写入响应正文，与put刚好相反
*/
func get(w http.ResponseWriter, r *http.Request) {

	file := getFile(strings.Split(r.URL.EscapedPath(), "/")[2])
	if file == "" {
		log.Println("file not found")
		w.WriteHeader(http.StatusNotFound)
		return
	}

	sendFile(w, file)

}

func getFile(name string) string {

	files, _ := filepath.Glob(os.Getenv("STORAGE_ROOT") + "/objects/" + name + ".*")
	if len(files) != 1 {
		return ""

	}
	file := files[0]
	h := sha256.New()
	sendFile(h, file)
	//file := os.Getenv("STORAGE_ROOT") + "/objects/" + hash
	//f, _ := os.Open(file)
	d := url.PathEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
	hash := strings.Split(file, ".")[2]
	if d != hash {
		log.Println("object hash mismatch, remove", file)
		locate.Del(hash)
		os.Remove(file)
		return ""
	}
	return file
}

func sendFile(w io.Writer, file string) {
	f, e := os.Open(file)
	if e != nil {
		log.Println("open file error:", e)
		return
	}
	defer f.Close()

	gzipStream, e := gzip.NewReader(f)
	if e != nil {
		log.Println("gzip error:", e)
		return
	}

	io.Copy(w, gzipStream)
	gzipStream.Close()
}
